#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <string.h>

#define ERRLOG() printf("[file:%s][func:%s][line:%d]\n",__FILE__,__func__,__LINE__);
#define INFO(fmt,...) printf(fmt,##__VA_ARGS__);

typedef struct {
    int num;
    pthread_mutex_t mutex;
    pthread_cond_t  cond;
}mutex_msg;

int num=0;

pthread_cond_t cond;

void handler(int arg){
    // INFO("销毁条件变量\n");
    // pthread_cond_destroy(&cond);
    exit(0);
}

void* pthread_function(void *arg){
    pthread_detach(pthread_self());
    mutex_msg *msg = (mutex_msg *)arg;
    while(1){
        pthread_mutex_lock(&msg->mutex);
        num++;
        INFO("[num++]:%d\n",num);
        pthread_mutex_unlock(&msg->mutex);
        // pthread_cond_signal(&msg->cond);

        if(num>5){
            pthread_cond_broadcast(&msg->cond);
        }
        sleep(1);
    }
}

void* pthread_function2(void *arg){
    pthread_detach(pthread_self());
    mutex_msg *msg = (mutex_msg *)arg;
    int i=msg->num;
    while(1){
        pthread_mutex_lock(&msg->mutex);
        pthread_cond_wait(&msg->cond,&msg->mutex);
        num--;
        INFO("i:%d[num--]:%d\n",i,num);
        pthread_mutex_unlock(&msg->mutex);
        sleep(1);
    }
}

int main(int argc, char const *argv[])
{
    signal(SIGINT,handler);
    pthread_mutex_t mutex;

    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);

    mutex_msg msg;
    memset(&msg,0,sizeof(mutex_msg));
    msg.mutex=mutex;
    msg.cond=cond;

    pthread_t pthread,pthread2;
    if(pthread_create(&pthread,NULL,pthread_function,&msg)!=0){
        ERRLOG();
        exit(-1);
    }

    for(int i=0;i<5;i++){
        msg.num=i;
        if(pthread_create(&pthread2,NULL,pthread_function2,&msg)!=0){
            ERRLOG();
            exit(-1);
        }
        usleep(1000);
    }
    while(1);
    return 0;
}
